package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"net/http"

	"golang.org/x/net/html/charset"
	"golang.org/x/text/transform"
)

//响应
func main() {
	r, err := http.Get("http://baidu.com")
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = r.Body.Close()
	}()
	responseBody(r)
	status(r)
	header(r)
	encoding(r)
}

func responseBody(r *http.Response) {
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s", b)
}

//状态码
func status(r *http.Response) {
	fmt.Println(r.StatusCode) //状态码
	fmt.Println(r.Status)     //状态描述
}

//响应头
func header(r *http.Response) {
	fmt.Printf("r.Header: %v\n", r.Header.Get("content-type"))

}

//响应编码
func encoding(r *http.Response) {
	//一般content-type 会提供编码信息
	buffer := bufio.NewReader(r.Body)
	b, _ := buffer.Peek(1024)

	e, _, _ := charset.DetermineEncoding(b, r.Header.Get("content-type"))
	bodyReader := transform.NewReader(buffer, e.NewDecoder())
	content, _ := ioutil.ReadAll(bodyReader)
	fmt.Printf("%s", content)
}
